package com.surrealbananapeel.battleship;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
/**
 * This class is used for connecting to the server. The class creates, and
 * maintains a socket communication every time a game is played.
 * 
 * @author Emmett Little and Alberto Saavedra
 */
public class Connector
{
    private final String SERVER = "pason2.enel.ucalgary.ca";
    private final int PORT = 6130;
    
    private BufferedReader bin;
    private BufferedWriter bout;
    
    Socket socket;
    
    /**
     * Creates a new instance of this class while connecting to the socket. 
     */
    public Connector()
    {
        connect();
    }
    
    /**
     * This method gets a response from the server.
     * 
     * @param message The message that will be sent to the server.
     * @return A string with the response.
     */
    public String getResponse(String message)
    {
        if (message != null && !message.isEmpty())
        {
            write(message);
        }
        else
        {
            
        }
        return read();
    }
    
    /**
     * This method writes a string message to the socket.
     * 
     * @param message The string to write.
     */
    public void write(String message)
    {
        try
        {
            bout.write(message + "\r\n");
            bout.flush();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    
    /**
     * This method reads a String from the buffer.
     * 
     * @return The string read from the socket.
     */
    public String read()
    {
        String line = null;
        try
        {
            line = bin.readLine();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return line;
    }
    
    /**
     *This method connects to the server based on the Server and Point 
     *specifications.
     * 
     */
    public void connect()
    {
        try
        {
            socket = new Socket(SERVER, PORT);
            
            bin = new BufferedReader(new InputStreamReader(socket
                    .getInputStream()));
            bout = new BufferedWriter(new OutputStreamWriter(socket
                    .getOutputStream()));
            
            System.out.println(getResponse(""));
        }
        catch (IOException ie)
        {
            ie.printStackTrace();
        }
    }
    
    /**
     * This method closes the socket. 
     */
    public void close()
    {
        try
        {
            socket.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}
